<?php

namespace App\CustHub\Job;

use App\CustHub\Service\ChUserService;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\AsyncQueue\Job;
use function FriendsOfHyperf\Lock\lock;

class UserJob extends Job
{
    public array $params;

    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     */
    protected int $maxAttempts = 2;


    public function __construct(array $params)
    {
        $this->params = $params;
    }

    public function handle()
    {
        logger()->info('用户扫码登录注册',$this->params);

        $wxUser = \Hyperf\Collection\data_get($this->params,'wxUser');
        $tag = \Hyperf\Collection\data_get($this->params,'tag');
        $ip = \Hyperf\Collection\data_get($this->params,'ip');
        if(empty($wxUser) || empty($tag)){
            return false;
        }
        $key = 'su_user_save_lock:'.md5(json_encode($wxUser));
        $lock = lock($key,6);
        try {
            $lock->block(4);
            // 根据参数处理具体逻辑
            $userService = container()->get(ChUserService::class);
            return $userService->saveUser($wxUser,$tag,$ip);
        }catch (LockTimeoutException $e){
            logger()->info('用户扫码登录注册失败，锁被占用'.json_encode($wxUser,JSON_UNESCAPED_UNICODE));
            return false;
        } finally {
            $lock->release();
        }
    }
}